from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
import random, logging
from django_redis import get_redis_connection
from . import constants
from meiduo_mall.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.


logger = logging.getLogger('django')


class SMSCodeView(APIView):
    """发送短信验证码"""

    def get(self, request, mobile):
        """
        GET /sms_codes/(?P<mobile>1[3-9]\d{9})/
        :param request:
        :param mobile:
        :return:
        """
        # 连接redis数据库
        redis_conn = get_redis_connection('verify_codes')

        # 设置60秒内不允许重复发送短信验证码
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '发送短信过于频繁'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        # redis 管道的使用（存储 短信验证码 及 发送短信验证码请求间隔时间标志）
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 注意：使用redis管道后，一定要加上pl.execute()，以来执行管道
        pl.execute()

        # 使用容联云通讯发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60], 1)
        # send_sms_code.delay(mobile, sms_code)

        # 响应结果
        return Response({'message': 'OK'})
